require "Object"

--LingDang class
ScoreBoard = Object:new{
	world = nil,
}

function ScoreBoard:onEnter()
	Misc:log("ScoreBoard : onEnter .. " .. Misc:getNodeName(self))
	
	local score = tolua.cast(Misc:getChildByName(self, "score"), "CCLabelTTF")
	local heightScore = tolua.cast(Misc:getChildByName(self, "heightScore"), "CCLabelTTF")
	
	score:setString(score:getString() .. self.world.score)
	local heightScoreValue = CCUserDefault:sharedUserDefault():getIntegerForKey("HeightScore")
	if self.world.score > heightScoreValue then
		heightScoreValue = self.world.score
		CCUserDefault:sharedUserDefault():setIntegerForKey("HeightScore" , heightScoreValue)
		CCUserDefault:sharedUserDefault():flush()
	end
	heightScore:setString(heightScore:getString() .. heightScoreValue)
	
	--click event
	local replayBtn = tolua.cast(Misc:getChildByName(self, "replay"), "UIButton")
	local function clicked()
		self:removeFromParentAndCleanup(true)
		self.world:clear()
		
		local world = createWorld()
		local ccTransScene = CCTransitionFlipAngular:create(1, world)
		CCDirector:sharedDirector():replaceScene(ccTransScene)
	end
	replayBtn:registerScriptActiveHandler(clicked)
end

function ScoreBoard:onExit()
	Misc:log("ScoreBoard : onExit .. " .. Misc:getNodeName(self))
	
end

function ScoreBoard:create(score_boardFile, world, score_board)
	local newScoreBoard = score_board or ScoreBoard:new()
	
	newScoreBoard.world = world
	
	local cc2dNode = CC2DFileCache:sharedCC2DFileCache():addCC2DNode(score_boardFile)
	local ccScoreBoard = tolua.cast(cc2dNode:createCCNode(world:getParent()), "UIWidget")
	
	tolua.setpeer(ccScoreBoard, newScoreBoard)
	
	local function onEnterOrExit(eventType)
		if eventType == kCCNodeOnExit then
			ccScoreBoard:onExit()
		else
			ccScoreBoard:onEnter()
		end
	end
	
	ccScoreBoard:registerScriptHandler(onEnterOrExit)
	
	if ccScoreBoard:isRunning() then
		ccScoreBoard:onEnter()
	end
	return ccScoreBoard
end